package com.mjfeed.controller.api;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mjfeed.controller.BaseController;
import com.mjfeed.dto.api.ProductJSON;
import com.mjfeed.dto.api.ProductListJSON;
import com.mjfeed.entity.Product;
import com.mjfeed.service.ProductImageService;
import com.mjfeed.service.ProductService;
import com.mjfeed.util.Format;
import com.mjfeed.util.Pagination;
import com.mjfeed.util.ParamBean;

/**
 * @description 商品
 * @author zhaominglei
 * @date 2014年12月6日
 */
@Controller("apiProductController")
@RequestMapping("/api/product")
public class ProductController extends BaseController {
	@Resource(name="productService")
	private ProductService productService;
	@Resource(name="productImageService")
	private ProductImageService productImageService;
	
	@RequestMapping(value = "/all" ,method=RequestMethod.GET)
	public String all(HttpServletRequest request, HttpServletResponse response){
		List<Product> products = productService.getAll(Product.class);
		ProductListJSON productListJSON = productService.allToJSON(products);
		super.renderJson(response, productListJSON);
		return null;
	}
	
	@RequestMapping(value = "/list" ,method=RequestMethod.GET)
	public String list(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null) {
			return null;
		}
		paramBean.setUrl(getBasePath(request) + "api/product/list.shtml");
		int p = (Format.null2Zero(request.getParameter("p")) == 0) ? 1 : Format.null2Zero(request.getParameter("p"));
		paramBean.setPage(p);
		paramBean.setField("name");
		paramBean.setPageSize(APP_DEFAULT_PAGE_SIZE);
		Pagination<Product> pagination = productService.getPagination(paramBean);
		ProductListJSON productListJSON = productService.searchToJSON(pagination);
		super.renderJson(response, productListJSON);
		return null;
	}
	
	@RequestMapping(value = "/detail" ,method=RequestMethod.GET)
	public String detail(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response){
		if (paramBean == null || paramBean.getProductId() == null || paramBean.getProductId() < 0) {
			return null;
		}
		Product product = productService.getById(Product.class, paramBean.getProductId());
		ProductJSON productJSON = productService.detailToJSON(product);
		super.renderJson(response, productJSON);
		return null;
	}
}
